package com.ttbj.product.costsharing.imp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ttbj.api.costsharing.CostSharingService;
import com.ttbj.api.dto.CostSharingDto;
import com.ttbj.api.dto.CutPayCostDto;
import com.ttbj.api.dto.CutPayListData;
import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.QueryVO;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.yitong.YTFinancialService;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.core.util.DateUtils;
import com.ttbj.core.util.JsonUtil;
import com.ttbj.core.util.MarkNumUtil;
import com.ttbj.costsharing.dao.CostSharingMapper;
import com.ttbj.cutpaycost.dao.CutPayCostMapper;
import com.ttbj.cutpayrevoke.bean.po.CutPayRevoke;
import com.ttbj.cutpayrevoke.dao.CutPayRevokeMapper;
import com.ttbj.product.yitong.impl.YTFinancialServiceImpl;




@Service("costSharingService")
public class CostSharingImpl implements CostSharingService{
	
	@Autowired
	private CostSharingMapper costSharingMapper;
	@Autowired
	private CutPayCostMapper cutPayCostMapper;
	@Autowired
	private CutPayRevokeMapper cutPayRevokeMapper;
	@Autowired
	private YTFinancialService ytFinancialService;
	
	private static final Logger logger = LoggerFactory.getLogger(YTFinancialServiceImpl.class);
	
	private static final String PLATFORM_TYPE = "A";	//平台类型
	private static final String DRIVER_TYPE = "B";	//司机类型
	private static final String COMMNUM_TYPE = "C";	//企业类型
	
	@Override
	public List<CostSharingDto> findCostSharingInfoByPage(CostSharingDto costSharing, Page page)
			throws BusinessException {
		List<CostSharingDto> costSharingDtos = this.costSharingMapper.queryCostSharingInfoByPage(costSharing, page);
		return costSharingDtos;
	}
	
	@Override
	public Integer findCostSharingInfoByPageCount(CostSharingDto costSharing) throws BusinessException {
		Integer count = this.costSharingMapper.queryCostSharingInfoByPageCount(costSharing);
		return count;
	}
	
	@Override
	public List<CutPayCostDto> findEveryLastCutPayInfo(String paymentOrderNo, Page page) throws BusinessException {
		if (StringUtils.isBlank(paymentOrderNo)) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.PARAM_IS_NULL.code());
		}
		List<CutPayCostDto> cutPayCostDtos = this.cutPayCostMapper.queryEveryLastCutPayInfo(paymentOrderNo, page);
		return cutPayCostDtos;
	}
	
	
	@Override
	@Transactional
	public void batchCpRevoke(List<CutPayCostDto> cutPayCostDtos, String paymentOrderNo) throws Exception {
		logger.info("进入批量分账撤销操作........");
		CostSharingDto costsharing = null;
		List<CutPayRevoke> cutPayRevokeList = new ArrayList<>();
		//传入的是一个List<CutPayCostDto>，用于批量分账撤销和更改数据和金额
		for (int i = 0; i < cutPayCostDtos.size(); i++) {
			CutPayRevoke cutPayRevoke = new CutPayRevoke();
			CutPayListData cutPayListData = new CutPayListData();
			String orderNo = MarkNumUtil.getNo("RE");	//设置每一个分账撤销订单号
			//重新设置分账撤销的orderNo(分账订单号)，不能使用分账时的orderNo
			cutPayListData.setOrderNo(orderNo);
			cutPayListData.setCpOrderNo(cutPayCostDtos.get(i).getTransNo());
			cutPayListData.setAccountNo(cutPayCostDtos.get(i).getAccountNo());
			//使用分账撤销接口进行撤销操作
			Map<String, String> map = this.ytFinancialService.getYTFinancialResult(cutPayListData, 16, "cp_revoke");
			logger.info("分账撤销返回的status：{}，返回的data：{}", map.get("status"), map.get("data"));
			//如果返回的为1，则说明成功，成功后初始化costsharing对象和cutPayList
			if (map.get("status").equals("1")) {
				logger.info("分账撤销成功.....");
				costsharing = new CostSharingDto();	//初始化CostSharingDto对象
				//把最外层的json进行解析为Query对象
				QueryVO queryVO = (QueryVO) JsonUtil.jsonToBean(map.get("data"), QueryVO.class);
				//把data的json字符串数据转换为对象
				CutPayCostDto cutPay = (CutPayCostDto) JsonUtil.jsonToBean(map.get("data"), "data", CutPayCostDto.class);
				//分割字符串，取出A(平台),B(司机),C(企业)中其中一个
				String cpType = cutPayCostDtos.get(i).getCpType();
				if (cpType.equals(PLATFORM_TYPE)) {
					costsharing.setPlatFormCostSharing("0.00");	//设置平台金额为0.00
				}else if (cpType.equals(DRIVER_TYPE)) {
					costsharing.setDriverCostSharing("0.00");	//设置司机金额为0.00
				}else if (cpType.equals(COMMNUM_TYPE)) {
					costsharing.setCompanyCostSharing("0.00");	//设置司机金额为0.00
				}
				costsharing.setPaymentOrderNo(paymentOrderNo);	//设置支付订单号
				cutPay.setStatus("02");	//设置分账的状态为：02（分账撤销）
				cutPayRevoke.setReAmount(cutPay.getAmount());	//获取返回的分账撤销金额
				cutPayRevoke.setReRetInfo(queryVO.getRetInfo());	//获取分账撤销描述如：受理成功
				cutPayRevoke.setReRetCode(queryVO.getRetCode());	//获取分账撤销应答代码如：S000S
				cutPayRevoke.setReReqTime(DateUtils.getDateTimeStr(queryVO.getReqTime()));	//获取请求时间并格式化成yyyy-HH-dd HH:mm:ss
			}else if (map.get("status").equals("0")) {
				String[] str = map.get("data").split("\\|");
				cutPayRevoke.setReRetInfo(str[1]);	//获取分账撤销描述如：分账撤销失败
				cutPayRevoke.setReRetCode(str[2]);	//获取分账撤销应答代码如：BP006F
				cutPayRevoke.setReReqTime(DateUtils.getDateTimeStr(map.get("reqTime")));	//获取请求时间并格式化成yyyy-HH-dd HH:mm:ss
				cutPayRevoke.setReAmount(cutPayCostDtos.get(i).getAmount());	//获取分账撤销的金额
				logger.info("分账撤销异常，异常描述为:{}", str[1]);
			}
			cutPayRevoke.setReOrderNo(orderNo);	//把请求的订单号进行保存
			cutPayRevoke.setReTransNo(cutPayCostDtos.get(i).getTransNo());	//设置分账订单号（分账系统返回的）
			cutPayRevoke.setReStatus(map.get("status"));	//设置分账撤销的状态
			cutPayRevokeList.add(cutPayRevoke);
		}
		for (CutPayRevoke cp : cutPayRevokeList) {
			logger.info("分账撤销成功后的数据-reOrderNo：{}，reAmount：{}，reStatus：{}， transNo：{}，"
					+ "reRetInfo：{}，reRetCode：{}，reReqTime：{}", cp.getReOrderNo(), cp.getReAmount(), cp.getReStatus(), 
					cp.getReTransNo(), cp.getReRetInfo(), cp.getReRetCode(), cp.getReReqTime());
		}
		//保存分账撤销信息，
		int n =  this.cutPayRevokeMapper.insertCutPayRevokeInfo(cutPayRevokeList);	//this.cutPayCostMapper.updateBatchCpRevokeInfo(cutPayList);
		//当costsharing 不为null时，才更新
		if (null != costsharing) {
			//执行更新操作，更新平台或实际或企业的分成金额，设置为0.00，说明已把钱撤销掉
			int m = this.costSharingMapper.updateCostSharingCarriage(costsharing);
		}
		//如果n 大于 0，则说明更新数据成功
		if (n == 0) {
			throw new BusinessException("分账撤销操作失败", PlatFormErrorCode.DATA_SECURITY.code());
		}
	}
	
	
	@Override
	public void editCutPayCostStatus(String status, String transNo) throws BusinessException {
		int i = this.cutPayCostMapper.updateCutPayCostStatus(status, transNo);
	}
	
	@Override
	@Transactional
	public void addCostSharingInfo(CostSharingDto costSharing) throws BusinessException {
		//增加分成信息
		int row = this.costSharingMapper.insertCostSharingInfo(costSharing);
		if (row == 0) {
			throw new BusinessException("添加分成信息失败！", PlatFormErrorCode.DATA_SECURITY.code());
		}
	}

	@Override
	public List<CostSharingDto> findCostSharingDayOrMonthStatistics(String format, String startDate, String endDate, Integer type)
			throws BusinessException {
		List<CostSharingDto> costSharingDtos = this.costSharingMapper.queryCostSharingDayOrMonthStatistics(format, 
								startDate.trim(), endDate, type);
		return costSharingDtos;
	}

}
